package bb.lanxing.lib.devices.core.utils;

import bb.lanxing.lib.devices.api.ConnectionListener;
import bb.lanxing.lib.devices.api.SmartDevice;
//import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArrayList;

public class ConnectionStateNotifier {
    private volatile CopyOnWriteArrayList<ConnectionListener> mListenerSet = new CopyOnWriteArrayList<>();

    public synchronized void notifyStateChanged(SmartDevice smartDevice, int i, int errCode) {
        if (this.mListenerSet != null) {
            try {
                for (ConnectionListener next : this.mListenerSet) {
                    if (next != null) {
                        next.onConnectionStateChanged(smartDevice, i, errCode);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public synchronized void registerConnectionListener(ConnectionListener connectionListener) {
        if (connectionListener != null) {
            if (!this.mListenerSet.contains(connectionListener)) {
                try {
                    this.mListenerSet.add(connectionListener);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public synchronized void unregisterConnectionListener(ConnectionListener connectionListener) {
        if (connectionListener != null) {
            if (this.mListenerSet != null && !this.mListenerSet.isEmpty() && this.mListenerSet.contains(connectionListener)) {
                try {
                    this.mListenerSet.remove(connectionListener);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public boolean isEmpty() {
        return this.mListenerSet != null && this.mListenerSet.isEmpty();
    }

    public synchronized void removeAllListeners() {
        if (this.mListenerSet != null) {
            this.mListenerSet.clear();
        }
        this.mListenerSet = null;
    }
}
